package com.amado.course35Concurrent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.*;

/**
 * 信号量用来做限流
 * Created by Administrator on 2018\3\18 0018.
 */
public class S17SemaphoreTest {
	private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(" HH:mm:ss");
	static Semaphore semaphore = new Semaphore(2);
	public static void main(String[] args) {
		new Thread(()->{
			for (int i = 0; i < 100; i++) {
				print();
			}
		}).start();
		new Thread(()->{
			for (int i = 0; i < 10; i++) {
				print();
			}
		}).start();
		new Thread(()->{
			for (int i = 0; i < 10; i++) {
				print();
			}
		}).start();
		new Thread(()->{
			for (int i = 0; i < 10; i++) {
				print();
			}
		}).start();
	}

	/**
	 * 控制同一时间只有1 (n)个线程可能访问
	 */
	private static void print(){
		try {
			semaphore.acquire();
			System.out.println(Thread.currentThread().getName()+simpleDateFormat.format(new Date()));
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			semaphore.release();
		}
	}
}
